
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include    <QTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_ble = new BLE(this);
    /* 蓝牙信号连接 */
    connect(m_ble,&BLE::signal_bluetoothrevdata,this,&MainWindow::deal_bluetooth_data);
    connect(m_ble,&BLE::signal_scanFinished,[=]{
        auto list = m_ble->getDevices();
        if(list.isEmpty())
            return ;
        ui->listWidget_dev_2->clear();
        for(auto s : list){
            ui->listWidget_dev_2->addItem(s.name()+' '+s.address().toString());
        }
    });
    connect(m_ble,&BLE::signal_findservicesFinished,[=]{
        auto list = m_ble->getServicesUUID();
        if(list.isEmpty())
            return ;
        ui->listWidget_services_2->clear();
        for(auto s : list){
            ui->listWidget_services_2->addItem(s.toString());
        }
    });
    connect(m_ble,&BLE::signal_findcharsFinished,[=]{
        auto list = m_ble->getChars();
        if(list.isEmpty())
            return ;
        ui->listWidget_character_2->clear();
        for(auto s : list){
            ui->listWidget_character_2->addItem(s.uuid().toString());
        }

    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::append(int type, const QString &data, bool clear)
{
    static int currentCount = 0;
    static int maxCount = 100;

    if (clear) {
        ui->textCOM->clear();
        currentCount = 0;
        return;
    }

    if (currentCount >= maxCount) {
        ui->textCOM->clear();
        currentCount = 0;
    }

//    if (!isShow) {
//        return;
//    }

    //过滤回车换行符
    QString strData = data;
    strData = strData.replace("\r", "");
    strData = strData.replace("\n", "");

    //不同类型不同颜色显示
    QString strType;
    if (type == 0) {
        strType = "串口发送 >>";
        ui->textCOM->setTextColor(QColor("blue"));
    } else if (type == 1) {
        strType = "串口接收 <<";
        ui->textCOM->setTextColor(QColor("red"));
    } else if (type == 2) {
        strType = "处理延时 >>";
        ui->textCOM->setTextColor(QColor("gray"));
    } else if (type == 3) {
        strType = "正在校验 >>";
        ui->textCOM->setTextColor(QColor("green"));
    } else if (type == 4) {
        strType = "网络发送 >>";
        ui->textCOM->setTextColor(QColor(24, 189, 155));
    } else if (type == 5) {
        strType = "网络接收 <<";
        ui->textCOM->setTextColor(QColor(255, 107, 107));
    } else if (type == 6) {
        strType = "提示信息 >>";
        ui->textCOM->setTextColor(QColor(100, 184, 255));
    }  else if (type == 7) {
        strType = "蓝牙接收 >>";
        ui->textCOM->setTextColor(QColor(188 ,143 ,143));
    }  else if (type == 8) {
        strType = "蓝牙发送 >>";
        ui->textCOM->setTextColor(QColor(84,255,159));
    }


    strData = QString("时间[%1] %2 %3").arg(TIMEMS).arg(strType).arg(strData);
    ui->textCOM->append(strData);
    currentCount++;
}

void MainWindow::on_pushButton_scan_clicked()
{
    ui->listWidget_dev_2->clear();
    ui->listWidget_services_2->clear();
    if(!m_ble->getScanning())
        m_ble->startScanDevices();
}




void MainWindow::on_pushButton_connect_clicked()
{
    if( ui->listWidget_dev_2->count()==0|| !(ui->listWidget_dev_2->currentItem()))
        return;
    auto list = m_ble->getDevices();
    if(list.isEmpty())
    {
        return;
    }
    auto s = list.at(ui->listWidget_dev_2->currentIndex().row());

    m_ble->connectDevice(s.address().toString());
}


void MainWindow::on_pushButton_service_clicked()
{
    if( ui->listWidget_services_2->count()==0 || !(ui->listWidget_services_2->currentItem()))
        return;
    QString vlaue = ui->listWidget_services_2->currentItem()->text();
    if(vlaue.isEmpty()||vlaue.isNull())
        return;
    m_ble->connectService(vlaue);
}

static QString byteArrayToHexStr(const QByteArray &data)
{
    QString temp = "";
    QString hex = data.toHex();
    for (int i = 0; i < hex.length(); i = i + 2) {
        temp += hex.mid(i, 2) + " ";
    }
    return temp.trimmed().toUpper();
}

char hexStrToChar(char data)
{
    if ((data >= '0') && (data <= '9')) {
        return data - 0x30;
    } else if ((data >= 'A') && (data <= 'F')) {
        return data - 'A' + 10;
    } else if ((data >= 'a') && (data <= 'f')) {
        return data - 'a' + 10;
    } else {
        return (-1);
    }
}

QByteArray hexStrToByteArray(const QString &data)
{
    QByteArray senddata;
    int hexdata, lowhexdata;
    int hexdatalen = 0;
    int len = data.length();
    senddata.resize(len / 2);
    char lstr, hstr;

    for (int i = 0; i < len;) {
        hstr = data.at(i).toLatin1();
        if (hstr == ' ') {
            i++;
            continue;
        }

        i++;
        if (i >= len) {
            break;
        }

        lstr = data.at(i).toLatin1();
        hexdata = hexStrToChar(hstr);
        lowhexdata = hexStrToChar(lstr);

        if ((hexdata == 16) || (lowhexdata == 16)) {
            break;
        } else {
            hexdata = hexdata * 16 + lowhexdata;
        }

        i++;
        senddata[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }

    senddata.resize(hexdatalen);
    return senddata;
}

void MainWindow::deal_bluetooth_data(const QByteArray &data)
{
    QString buffer;
    buffer = byteArrayToHexStr(data);
    append(7, buffer);
}

void MainWindow::on_bt_send_clicked()
{
    QString str = ui->cboxData->currentText();
//    if (str.isEmpty()) {
//        ui->cboxData->setFocus();
//        return;
//    }
    for (int k=0;k<1000 ;k++ ) {
        str+= QString::number(k);
    }

    QByteArray bytes = hexStrToByteArray(str);
    // QString转QByteArray方法1
    int len = bytes.length();
    m_ble->senddata(bytes);
    append(8, str);
}

